import 'dart:convert' as convert;
import 'dart:convert';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:device_information/device_information.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:mac_address/mac_address.dart';
import 'package:path/path.dart' as path;
import 'package:provider/provider.dart';
import 'package:xvideos/alert_business/normal_alert_style.dart';
import 'package:xvideos/alert_business/splash/sys_domain_error_alert.dart';
import 'package:xvideos/alert_business/splash/update_dialog.dart';
import 'package:xvideos/config/address.dart';
import 'package:xvideos/config/config.dart';
import 'package:xvideos/config/varibel_config.dart';
import 'package:xvideos/hj_model/splash/ads_model.dart';
import 'package:xvideos/hj_model/splash/cut_info.dart';
import 'package:xvideos/hj_model/splash/domain_source_model.dart';
import 'package:xvideos/hj_model/user/user_info_model.dart';
import 'package:xvideos/hj_page/main_page/main_page_page.dart';
import 'package:xvideos/hj_page/main_page/provider/ai_bubble_provider.dart';
import 'package:xvideos/hj_page/pre_sale/limit_time_event/limit_time_event_provider.dart';
import 'package:xvideos/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:xvideos/hj_utils/api_service/common_service.dart';
import 'package:xvideos/hj_utils/detect_line_manager.dart';
import 'package:xvideos/hj_utils/event_tracking_manager.dart';
import 'package:xvideos/hj_utils/holiday_theme.dart';
import 'package:xvideos/hj_utils/light_model.dart';
import 'package:xvideos/hj_utils/local_server.dart';
import 'package:xvideos/hj_utils/local_server_guard.dart';
import 'package:xvideos/hj_utils/store_keys.dart';
import 'package:xvideos/hj_utils/text_util.dart';
import 'package:xvideos/hj_utils/utils.dart';
import 'package:xvideos/hj_utils/version_util.dart';
import 'package:xvideos/tools_base/debug_log.dart';
import 'package:xvideos/tools_base/global_store/local_ads_info_store.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/net/api_exception.dart';
import 'package:xvideos/tools_base/net/net_manager.dart';
import 'package:xvideos/tools_base/widget/LoadingWidget.dart';

import '../../hj_utils/free_play_count_manager.dart';
import '../live/live_main_page.dart';
import '../main_page/provider/msg_provider.dart';

//启动页
class SplashLogic extends GetxController {
  bool hasSetGesture = true;
  List<AdsInfoModel>? adsInfoBean;
  bool adLoadFinish = false;
  LocalServerGuard? localServerGuard;
  int isDataLoadFinishTask = 0;
  bool isJumpToHome = false;

  @override
  onReady() {
    super.onReady();
    _initStatus();
  }

  Future _initStatus() async {
    await getDeviceInfo(); //获取设备信息
    netManager.clearUserAgent(); //清除老的ua
    _showAds(isBefore: true); //获取上次启动的广告
    String? line = await _checkNetAlways(); //选线
    initialProcess(line); //初始化流程
  }

  initialProcess(String? line) async {
    assert(TextUtil.isNotEmpty(line));
    // 初始化网络层
    _initNetManager(line!);
    // token或者设备id登陆,先登录，后升级，不然渠道一升级就没有量了
    UserInfoModel? userInfo = await _devLogin();

    // 获取远程配置
    List<CheckVersionInfo> listVersion = await _getRemoteConfig();
    PreSaleProvider().refreshPreSaleConfig();

    await _checkUpdate(listVersion); // 检查更新
    await FreePlayCountManager().initConfig();
    MineMsgProvider.isShowNewerAlertFirst();
    EventTrackingManager.analytics.init(
      "e37dc758420fa088638d96af49e378a6",
      userId: userInfo?.uid.toString(),
    );
    _initLocalServer(); // 初始化localserver缓存
    getHomeTagList(); //获取模块
  }

  getDeviceInfo() async {
    String? imei;
    String? macAddress;
    try {
      macAddress = await GetMac.macAddress;
      imei = await DeviceInformation.deviceIMEINumber;
    } catch (e) {
      debugLog(e);
    }
    Config.imei = imei;
    Config.macAddress = macAddress;
  }

  ///isBefore = true 取出上次展示的广告
  _showAds({bool isBefore = true}) async {
    List<AdsInfoModel> adsList;
    if (isBefore) {
      adsList = await getAdvBeforeByType(1);
    } else {
      adsList = await getAdvByType(1);
    }
    adsInfoBean = adsList;
    adLoadFinish = true;
    update();
  }

  ///一直检查网络直到成功
  Future<String?> _checkNetAlways() async {
    LoadingWidget loadingWidget = LoadingWidget(title: "选线中...");
    loadingWidget.show();

    var result = await Connectivity().checkConnectivity();
    // 有网络,开始选线
    if (result != ConnectivityResult.none) {
      var line = await DetectLineManager().detectLineOnce();
      loadingWidget.cancel();
      if (TextUtil.isNotEmpty(line)) return line;
    }
    await SysDomainErrorAlert.show(callback: () async {
      // await _getNewDomain();
      var line = await DetectLineManager().detectLineOnce();
      loadingWidget.cancel();
      if (TextUtil.isNotEmpty(line)) initialProcess(line); //初始化流程
    }).then((value) {
      loadingWidget.cancel();
    });
    return null;
  }

  _initNetManager(String host) {
    Address.baseHost = host;
    Address.baseApiPath = path.join(Address.baseHost ?? "", Address.API_PREFIX);
    netManager.init(Address.baseApiPath ?? "");
  }

  ///登录
  Future<UserInfoModel?> _devLogin() async {
    String? cutInfos = "";
    try {
      var channel = await getChannel();
      if (TextUtil.isNotEmpty(channel)) {
        // await showConfirm(context, title: "检测到渠道号:$channel");
        CutInfo cutInfo = CutInfo()..dc = channel;
        cutInfos = json.encode(cutInfo.toJson());
      } else {
        ClipboardData? clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
        if (TextUtil.isNotEmpty(clipboardData?.text)) {
          cutInfos = clipboardData?.text;
        }
      }
    } catch (e) {
      debugLog('getChannel', e.toString());
    }
    String? deviceId = await getDeviceOaid();
    await netManager.userAgent(deviceId: deviceId);

    UserInfoModel? userInfo;
    while (true) {
      if (userInfo != null) {
        break;
      }
      userInfo = await globalStore.loginByDevice(deviceId, paste: cutInfos ?? "");
      if (userInfo == null) {
        var result = await showConfirm(
          content: "登录失败，是否重试?",
          showCancelBtn: true,
        );
        if (result != true) {
          // 点了取消退出循环
          break;
        }
      }
    }
    return userInfo;
  }

  Future<List<CheckVersionInfo>> _getRemoteConfig() async {
    List<CheckVersionInfo>? checkVersionList;
    while (true) {
      if (checkVersionList != null) {
        break;
      }
      try {
        DomainSourceModel info = await CommonService.fetchRemoteConfig();
        await _updateDomainInfo(info);
        await _configAdsInfo(info.ads?.adsInfoList);

        await _showAds(isBefore: false);
        // ai 女友冒泡
        Get.context?.read<AIBubbleProvider>().aiBubble = info.aiBubble;

        Config.adsTimeLongVideo = info.adsTimeLongVideo ?? 0;
        Config.aiUndressPrice = info.aiUndressPrice;
        Config.aiChangeFaceImgPrice = info.aiChangeFaceImgPrice;
        Config.aiGirlFriend = info.aiGirlFriend ?? true;
        Config.userAwards = info.userAwards ?? [];
        Config.sendMsgPrice = info.sendMsgPrice ?? 0;

        ///配置公告
        Config.systemConfigs = info.systemConfigList;
        Config.storeIsOpen = info.storeIsOpen ?? false;

        ///埋点域名
        if (info.dataBuriedPoint == null) {
          Config.dataBuriedPoint = "";
        } else {
          Config.dataBuriedPoint = info.dataBuriedPoint;
        }

        if (info.activeUrl == null) {
          Config.activeUrl = "";
        } else {
          Config.activeUrl = info.activeUrl;
        }

        Config.jgArea = info.jgArea;

        Config.gameActivityPopUp = info.gameActivityPopUp;
        Config.ver = info.ver ?? [];

        checkVersionList = info.ver ?? [];
        //直播模块开关
        LiveMainPage.broadcast = info.broadcast ?? false;
        //预售相关
        presaleProvider.advanceStatus = info.advanceStatus;
        presaleProvider.advancePage = info.advancePage;
        //幸运抽奖相关
        presaleProvider.luckyDrawH5 = info.luckyDrawH5;
        presaleProvider.luckyDrawIcon = info.luckyDrawIcon;

        //限时活动相关
        limitTimeProvider.bannerJump = info.bannerJump;
        Config.proxyBannerJump = info.proxyBannerJump;
        // holidayTheme.setThemeValue(info.festivalUi ?? '');
        holidayTheme.setThemeValue('默认');
        Config.hotSearchTerms = info.hotSearchTerms ?? [];

        Config.darkWebVipId = info.darkWebVipId;
        Config.darkWebVipName = info.darkWebVipName;
        Config.recommendVipIds = info.recommendVipIds;
      } catch (e) {
        debugLog('getRemoteConfig', e.toString());
        var result = await showConfirm(content: "获取配置信息失败${(e is ApiException) ? e.code : 1500}，是否重试?", showCancelBtn: true);
        if (result != true) {
          break;
        }
      }
    }
    return checkVersionList ?? [];
  }

  /////更新数据
  _updateDomainInfo(DomainSourceModel domainSourceModel) async {
    //域名列表信息
    VariableConfig.totalWatch = domainSourceModel.totalWatch;
    List<Sourcelist>? sourceLists = domainSourceModel.sourceList;

    if (sourceLists!.isEmpty) {
      String source = await lightKV.getString(StoreKeys.SOURCE_INFO) ?? "";
      if (source.isNotEmpty) {
        sourceLists = convert.jsonDecode(source);
      }
    }
    for (Sourcelist sourceBean in sourceLists!) {
      switch (sourceBean.type) {
        case "SHARE":
          Address.shareUrlNew = sourceBean.domain?.first.url;
          break;
        case "IMAGE":
          Address.baseImagePath = sourceBean.domain![0].url;
          break;
        case "GROUP":
          Address.baseGroupUrl = sourceBean.domain![0].url;
          break;
        case "TELEGRAM":
          Address.groupTelegram = sourceBean.domain![0].url;
          break;
        case "VID":
          Address.cdnAddressLists = sourceBean.domain!;
          Address.cdnAddress = Address.cdnAddressLists[0].url;
          break;
        case "GUIDE":
          Address.groundURl = sourceBean.domain![0].url;
          break;
        case "AppStore": //福利中心应用中心
          Address.appCenterUrl = sourceBean.domain![0].url;
          break;
        case 'AUDIO':
          Address.audioCdnAddress = sourceBean.domain?.firstOrNull?.url;
          break;
      }
    }

    Config.wordAdsBeans = domainSourceModel.ads?.announList ?? [];
  }

  ///检查是否需要更新
  Future _checkUpdate(List<CheckVersionInfo> versionList) async {
    if (versionList.isEmpty) return;
    //存储更新信息,然后检测
    lightKV.setString(StoreKeys.UPDATE_INFO, convert.jsonEncode(versionList));

    String phoneStr = Platform.operatingSystem;
    CheckVersionInfo? phoneBean;
    for (CheckVersionInfo bean in versionList) {
      if (bean.platform?.toLowerCase() == phoneStr) {
        phoneBean = bean;
        break;
      }
    }
    if (phoneBean == null) return;
    //是否需要更新
    Map<String, dynamic> map = await checkUpdate();
    bool isNeedUpdate = map['isNeedUpdate'] ?? false;
    if (isNeedUpdate) {
      // 用户是否点了更新
      bool? update = await UpdateDialog.show(phoneBean);
      if (!(update ?? false) && phoneBean.forcedUpdate == true) {
        await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
        return;
      }
    }
  }

  Future _initLocalServer() async {
    //启动本地服务并配置registry
    CacheServer cacheServer = CacheServer(
      cacheManager: null,
      openSubManager: true,
    );
    // 启动localserver守护进程
    localServerGuard = LocalServerGuard(cacheServer);
    await localServerGuard?.run();
    /*cacheServer.addReqFilter(LOCAL_M3U8_FILTER, Address.baseHost,
        pathPrefix: Address.API_PREFIX + Address.VIDEO_SUFFIX,
        hb: _headerBuilder);*/
    // ts 过滤，设置ts请求地址
    //cacheServer.addReqFilter(LOCAL_TS_FILTER, Address.cdnAddress);
    //其余任意文件拦截
    cacheServer.addReqFilter(LOCAL_ALL_FILTER, Address.baseImagePath!);
    //cacheServer.registerErrCallBack(failedCallback);
    //cacheServer.onLocalServerIdel = recommendListModel.getNeedCachedUrl;
    //cacheServer.onJoinSubCache = CachedVideoStore().inCachedList;

    // 这个ttl是m3u8列表里面的一个加密的key，要放到外面请求
    /*cacheServer.addCustomResponse(
      Config.M3U8_KEY_SECRET,
      _handleTTLSec,
    );

    cacheServer.addCustomResponse(Config.M3U8_MT_KEY_SECRET, _handleMTSec);

    cacheServer.addCustomResponse(Config.M3U8_PMS_KEY_SECRET, _handlePMSSec);*/
  }

  Future getHomeTagList() async {
    Config.plateModule = await CommonService.getTagsMarkList();
    final model = Config.plateModule?.community?.where((element) => element.needCheck);
    if (model != null) {
      model.forEach((element) {
        CommonService.checkModulesOrSectionConfig(element.id ?? '').then((value) {
          if (value != null) {
            element.hasPay = value.hasPay;
          }
        });
      });
    }
    isDataLoadFinishTask++;
    jumpToHomeJudgeEvent();
  }

  Future<void> jumpToHomeJudgeEvent({bool checkLock = true}) async {
    if (isJumpToHome && isDataLoadFinishTask > 0) {
      Get.offAllNamed(MainPage.routeName);
    }
  }
}

//广告信息配置
Future _configAdsInfo(List<AdsInfoModel>? adsList) async {
  adsList?.forEach((model) {
    if (model.cover?.startsWith("http") == true) {
      Uri? uri = Uri.tryParse(model.cover ?? "");
      model.cover = path.join(Address.baseImagePath ?? "", uri?.path);
    } else {
      model.cover = path.join(Address.baseImagePath ?? "", model.cover);
    }
  });
  return LocalAdsStore().setAdsList(adsList);
}
